package cn.zhouyafeng.itchat4j.gui;

import cn.zhouyafeng.itchat4j.api.MessageTools;
import cn.zhouyafeng.itchat4j.api.WechatTools;
import cn.zhouyafeng.itchat4j.beans.BaseMsg;
import cn.zhouyafeng.itchat4j.face.IMsgHandlerFace;
import cn.zhouyafeng.itchat4j.utils.SleepUtils;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.config.Global;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.utils.SpringUtils;
import com.jeesite.modules.wxrobot.ActivityConstants;
import com.jeesite.modules.wxrobot.entity.Customer;
import com.jeesite.modules.wxrobot.entity.TaskActivity;
import com.jeesite.modules.wxrobot.service.CustomerService;
import com.jeesite.modules.wxrobot.service.TaskActivityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;

import java.util.List;
import java.util.Map;

/**
 * 简单示例程序，收到文本信息自动回复原信息，收到图片、语音、小视频后根据路径自动保存
 *
 * @author https://github.com/yaphone
 * @date 创建时间：2017年4月28日 下午10:50:36
 * @version 1.0
 *
 */
public class PersonalFissionMsgHandler implements IMsgHandlerFace {
	private static final Logger logger = LoggerFactory.getLogger(PersonalFissionMsgHandler.class);
	@Override
	public String textMsgHandle(BaseMsg msg) {

		//群消息直接放开
		if (msg.getFromUserName().startsWith("@@")) {
			return "";
		}
		String text = msg.getText();
		/*
        得到用户发送的邀请码
        1、获取机器人运行的活动配置（活动id，邀请码长度，正确邀请码回复，错误邀请码回复）
        2、验证用户是否已发送过邀请码成为了客户，已成为客户则正常聊天，否则下一步骤
        3、验证邀请码是否合格（长度匹配，邀请码对应的客户信息存在）
        4、合格则发送正确邀请码回复，
            上级的子集数+1
            生成专属码
            插入活动客户信息
            发送含用户专属码的活动海报
            发送消息给上级用户提示新增助力
            修改用户备注名
        5、不合格则发送错误邀请码回复
         */

		TaskActivityService taskActivityService = SpringUtils.getBean(TaskActivityService.class);
		TaskActivity taskActivity = taskActivityService.getByRobotWeixin(msg.getToUserName());
		if (taskActivity == null) {
			return null;
		}

		//不是邀请码，直接放开，正常聊天
		if (!text.startsWith(taskActivity.getPrefixCode())) {
			return "";
		}

		//根据用户备注名，查找客户，如果已存在，则正常聊天，否则走成为客户的逻辑
		List<JSONObject> contactList = WechatTools.getContactList();
		String remarkName = null;
		String nickName = null;
		for (JSONObject jsonObject : contactList) {
			String userName = jsonObject.getString("UserName");
			if (userName.equals(msg.getFromUserName())) {
				nickName = jsonObject.getString("NickName");
				remarkName = nickName + "-" + jsonObject.getString("Signature");//昵称 + '-' + 签名
			}
		}
		Customer cusCond = new Customer();
		CustomerService customerService = SpringUtils.getBean(CustomerService.class);
		if (StringUtils.isNotBlank(remarkName)) {
			cusCond.setRemarkName(remarkName);
			cusCond.setActivityId(taskActivity.getId());
			List<Customer> thisCuses = customerService.findList(cusCond);
			//已成为该活动客户，可正常聊天
			if (thisCuses != null && thisCuses.size() > 0) {
				return "";
			}
		}


		String realPath = getRealPath();

		//if (text.length() == activityReply.getActivity().getInvitationLength().intValue()) {
			//获取邀请码对应的客户
			cusCond = new Customer();
			cusCond.setActivityId(taskActivity.getId());
			cusCond.setSelfCode(text);

			List<Customer> parentCustomers = customerService.findList(cusCond);
			if (parentCustomers != null && parentCustomers.size() > 0) {
				//上级客户
				Customer parentCustomer = parentCustomers.get(0);

				//发送正确邀请码回复
				replyMessage(taskActivity, ActivityConstants.ReplyType.RIGHT_INVITATION.getCode(), realPath, msg.getFromUserName());
                /*
                上级的子集数+1
                生成专属码
                插入活动客户信息
                发送含用户专属码的活动海报
                发送消息给上级用户提示新增助力
                修改用户微信备注名
                 */
				if (parentCustomer.getSubNum() != null) {
					parentCustomer.setSubNum(parentCustomer.getSubNum() + 1);
				} else {
					parentCustomer.setSubNum(1L);
				}

				//更新父级的下级数
				customerService.update(parentCustomer);
				//上级不是机器人，则发送消息给父级微信
				if (parentCustomer.getRobot().intValue() != 1) {
					//根据父级备注名找到微信用户名
					String parentWeixinUserName = null;
					for (JSONObject jsonObject : contactList) {
						if (parentCustomer.getRemarkName().equals(jsonObject.getString("NickName") + "-" + jsonObject.getString("Signature"))) {
							parentWeixinUserName = jsonObject.getString("UserName");
						}
					}
					if (StringUtils.isNotBlank(parentWeixinUserName)) {
						SleepUtils.sleep(3 * 1000); //休眠3秒
						replyMessage(parentWeixinUserName, String.format(Global.getConfig("robot.autoreply.assisted"), parentCustomer.getSubNum()));
						//助力数到达，回复配置的消息给用户
						if (parentCustomer.getSubNum().intValue() >= taskActivity.getHelps().intValue()) {
							replyMessage(taskActivity, ActivityConstants.ReplyType.HELP_ARRIVAL.getCode(), realPath, parentWeixinUserName);
						}
					}
				}



				String maxSelfCodeByActivityIdStr = "";
				String exclusivePosterPath = null;
				//邀请码不能重复，因此查询最大邀请码采用同步机制
				synchronized (this) {
					//生成用户专属码及专属海报
					//获取最大的专属码
					String maxSelfCodeByActivityId = customerService.getMaxSelfCodeByActivityId(taskActivity.getId());
					//获取专属码内的数字
					String numberCodeStr = maxSelfCodeByActivityId.substring(taskActivity.getPrefixCode().length());
					int numberCode = Integer.parseInt(numberCodeStr);
					numberCode++;
					maxSelfCodeByActivityIdStr += numberCode;
					//数字前面补零
					for (int i = 0; i < 4 - String.valueOf(numberCode).length(); i++) {
						maxSelfCodeByActivityIdStr = "0" + maxSelfCodeByActivityIdStr;
					}
					//前缀+(数字+1)
					maxSelfCodeByActivityIdStr = taskActivity.getPrefixCode() + maxSelfCodeByActivityIdStr;

					//插入机器人信息到客户表
					Customer ins = new Customer();
					ins.setActivityId(taskActivity.getId());
					//ins.setWeixinUserName(msg.getFromUserName());
					ins.setSubNum(0L);
					ins.setInvitationCode(text);
					ins.setSelfCode(maxSelfCodeByActivityIdStr);
					ins.setRemarkName(remarkName);
					ins.setNickName(nickName);
					customerService.save(ins);
				}

				Map<String, String> exclusivePoster = customerService.generateExclusivePoster(taskActivity.getId(), maxSelfCodeByActivityIdStr, realPath);
				exclusivePosterPath = exclusivePoster.get("exclusivePosterPath");

				logger.info("用户【{}】的专属海报为【{}】", nickName, exclusivePosterPath);
				SleepUtils.sleep(3 * 1000); //休眠3秒
				//发送专属海报给客户
				MessageTools.sendPicMsgByUserId(msg.getFromUserName(), exclusivePosterPath);
				replyMessage(msg.getFromUserName(), Global.getConfig("robot.autoreply.shareposter"));

				/*SleepUtils.sleep(8 * 1000); //休眠8秒
				//修改用户备注名
				WechatTools.remarkNameByUserName(msg.getFromUserName(), ins.getRemarkName());
				//修改缓存
				for (JSONObject jsonObject : contactList) {
					if (jsonObject.getString("UserName").equals(msg.getFromUserName())) {
						jsonObject.put("RemarkName", ins.getRemarkName());
					}
				}*/

			} else {
				String warnMsg = String.format("From【%s】邀请码【%s】无法找到对应用户", msg.getFromUserName(), text);
				logger.warn(warnMsg);
				//replyMessage(msg.getFromUserName(), errorInvitation);
				replyMessage(taskActivity, ActivityConstants.ReplyType.ERROR_INVITATION.getCode(), realPath, msg.getFromUserName());
			}
		//} else {
			//屏蔽错误邀请码回复
			//replyMessage(msg.getFromUserName(), errorInvitation);
		//}
		return "";
	}

	@Override
	public String picMsgHandle(BaseMsg msg) {
		/*String fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) + ".jpg"; // 这里使用收到图片的时间作为文件名
		String picPath = "D://itchat4j/pic" + File.separator + fileName; // 保存图片的路径
		DownloadTools.getDownloadFn(msg, MsgTypeEnum.PIC.getType(), picPath); // 调用此方法来保存图片
		return "图片保存成功";*/
		return "";
	}

	@Override
	public String voiceMsgHandle(BaseMsg msg) {
		/*String fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) + ".mp3"; // 这里使用收到语音的时间作为文件名
		String voicePath = "D://itchat4j/voice" + File.separator + fileName; // 保存语音的路径
		DownloadTools.getDownloadFn(msg, MsgTypeEnum.VOICE.getType(), voicePath); // 调用此方法来保存语音
		return "声音保存成功";*/
		return "";
	}

	@Override
	public String viedoMsgHandle(BaseMsg msg) {
		/*String fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) + ".mp4"; // 这里使用收到小视频的时间作为文件名
		String viedoPath = "D://itchat4j/viedo" + File.separator + fileName;// 保存小视频的路径
		DownloadTools.getDownloadFn(msg, MsgTypeEnum.VIEDO.getType(), viedoPath);// 调用此方法来保存小视频
		return "视频保存成功";*/
		return "";
	}

	@Override
	public String nameCardMsgHandle(BaseMsg arg0) {
//		return "收到名片消息";
		return "";
	}

	@Override
	public void sysMsgHandle(BaseMsg baseMsg) {

	}

	@Override
	public String verifyAddFriendMsgHandle(BaseMsg baseMsg) {
		MessageTools.addFriend(baseMsg, true);
		TaskActivityService taskActivityService = SpringUtils.getBean(TaskActivityService.class);
		TaskActivity taskActivity = taskActivityService.getByRobotWeixin(baseMsg.getToUserName());
		replyMessage(taskActivity, ActivityConstants.ReplyType.VERIFY_FRIEND.getCode(), getRealPath(), baseMsg.getRecommendInfo().getUserName());
		return "";
	}

	@Override
	public String mediaMsgHandle(BaseMsg baseMsg) {
		return null;
	}

	private void replyMessage(String toUserName, String content) {
		MessageTools.sendMsgById(content, toUserName);
	}

	/**
	 * 根据类型回复内容消息
	 */
	private void replyMessage(TaskActivity taskActivity, int replyType, String realPath, String toUserName) {
		//好友应答回复
		if (replyType == ActivityConstants.ReplyType.VERIFY_FRIEND.getCode()) {
			reply(taskActivity.getFriendsText(), taskActivity.getFriendsPic(), taskActivity.getFriendsGroupInvitation(), realPath, toUserName);
		} else if (replyType == ActivityConstants.ReplyType.RIGHT_INVITATION.getCode()) {
			reply(taskActivity.getRightCodeText(), taskActivity.getRightCodePic(), taskActivity.getRightCodeGroupInvitation(), realPath, toUserName);
		} else if (replyType == ActivityConstants.ReplyType.ERROR_INVITATION.getCode()) {
			reply(taskActivity.getErrorCodeText(), taskActivity.getErrorCodePic(), taskActivity.getErrorCodeGroupInvitation(), realPath, toUserName);
		} else if (replyType == ActivityConstants.ReplyType.HELP_ARRIVAL.getCode()) {
			reply(taskActivity.getHelpsArrivalText(), taskActivity.getHelpsArrivalPic(), taskActivity.getHelpsArrivalGroupInvitation(), realPath, toUserName);
		}
	}

	private void reply(String text, String pic, String groupInvitation, String realPath, String toUserName) {
		if (StringUtils.isNotBlank(text)) {
			MessageTools.sendMsgById(text, toUserName);
		}
		if (StringUtils.isNotBlank(pic)) {
			MessageTools.sendPicMsgByUserId(toUserName, realPath + pic);
		}
		if (StringUtils.isNotBlank(groupInvitation)) {
			List<JSONObject> groupList = WechatTools.getGroupList();
			for (JSONObject jsonObject : groupList) {
				if (jsonObject.getString("NickName").equals(groupInvitation)) {
					MessageTools.addChatRoomMember(jsonObject.getString("UserName"), toUserName);
					break;
				}
			}
		}
	}

	private String getRealPath() {
		WebApplicationContext applicationContext = (WebApplicationContext) SpringUtils.getApplicationContext();
		String realPath = applicationContext.getServletContext().getRealPath("/");
		realPath = realPath.replaceAll("\\\\", "/");
		if (realPath.endsWith("/")) {
			realPath = realPath.substring(0, realPath.length() - 1);
		}
		return realPath;
	}

}
